<?php

declare(strict_types=1);
namespace ImiApp\WebSocketServer\OtherServer;

use Imi\Server\Http\Controller\HttpController;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Imi\Server\View\Annotation\View;
use Imi\Server\WebSocket\Route\Annotation\WSConfig;

use Imi\ConnectionContext;
use Imi\Cache\CacheManager as Cache;

// use Imi\ConnectContext;

/**
 * 测试.
 *
 * @Controller
 * @View(renderType="html")
 */
class HandShakeController extends HttpController
{
    /**
     * @Action
     * @Route("/ws")
     * @WSConfig(parserClass=\Imi\Server\DataParser\JsonArrayParser::class)
     *
     * @return void
     */
    public function ws()
    {

        /** @var \Imi\Server\Http\Message\Request $request */
        $request = \Imi\RequestContext::get('request');
       
        $token = $request->get('token');
        if(!$token){
            $currentFd = $this->request->getSwooleRequest()->fd;
            return $this->request->getServerInstance()->getSwooleServer()->close($currentFd);
        }
        var_dump('token:', $token);
        //找用户

        $user = Cache::get('redis', $token);
        // if ($user = ConnectionContext::get($token)) {

        // }
        $currentFd = $this->request->getSwooleRequest()->fd;
        // var_dump('user',$user);
        if (!$user) {
            var_dump('ws没有登录！', $token);            
            return $this->request->getServerInstance()->getSwooleServer()->close($currentFd);
        }

        ConnectionContext::set('user_id', $user['id']);
        $flag = 'user_id-' . $user['id'];

        var_dump('im/握手', $flag, 'currentFd' . $currentFd);

        // if(!ConnectContext::bindNx($flag, $currentFd))//绑定连接，如果已绑定返回false
        // {
        //     $fd = ConnectContext::getFdByFlag($flag);//使用标记（UID）获取连接编号
        //     if($fd)
        //     {
        //         // $this->request->getServerInstance()->getSwooleServer()->close($fd);
        //     }
        //     if(!ConnectContext::bindNx($flag, $currentFd))
        //     {
        //         // $this->request->getServerInstance()->getSwooleServer()->close($currentFd);
        //     }
        // }

        var_dump('ImiApp\WebSocketServer\OtherServer HandShakeController user_id', ConnectionContext::get('user_id'));
        // 握手处理，什么都不做，框架会帮你做好
    }
}
